package com.kkb.mybatis.framework.builder;

import com.kkb.mybatis.framework.config.Configuration;
import com.kkb.mybatis.framework.config.MappedStatement;
import com.kkb.mybatis.framework.sqlsource.SqlSource;
import com.kkb.mybatis.utils.ReflectUtils;
import org.dom4j.Element;

/**
 *  该类用于解析statement标签
 */
public class XMLStatementBuilder {

    private Configuration configuration;

    public XMLStatementBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseStatementElement(Element element, String namespace) {
        String statementId = element.attributeValue("id");
        if (statementId == null || "".equals(statementId)) {
            return;
        }
        statementId = namespace + "." + statementId;
        String resultType = element.attributeValue("resultType");

        Class<?> resultTypeClazz = ReflectUtils.resolve(resultType);
        String statementType = element.attributeValue("statementType");
        statementType = statementType == null || "".equals(statementType) ? "prepared" : statementType;

        SqlSource sqlSource = createSqlSource(element);

        MappedStatement mappedStatement = new MappedStatement(statementId,statementType,resultType, resultTypeClazz,sqlSource);
        configuration.addMappedStatement(statementId, mappedStatement);
    }

    private SqlSource createSqlSource(Element element) {
        //解析所有sql节点，最终封装到mixedSqlNode中
        XMLScriptBuilder xmlScriptBuilder = new XMLScriptBuilder();
        SqlSource sqlSource = xmlScriptBuilder.parseScriptNode(element);
        return sqlSource;
    }
}
